import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import {
  Container,
  Paper,
  Typography,
  Box,
  Grid,
  Chip,
  Divider,
  CircularProgress,
  Alert,
  Snackbar,
} from '@mui/material';
import LocalOfferIcon from '@mui/icons-material/LocalOffer';
import { ResourceService } from '../services/ResourceService';
import { Resource } from '../types';
import ResourcePromotions from '../components/ResourcePromotions';
import { Button } from '@mui/material';
import { PromotionResourceService } from '../../../features/promotion/services/PromotionResourceService';
import { Promotion, PromotionService } from '../../../features/promotion/services/PromotionService';

const formatSize = (bytes: number): string => {
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  if (bytes === 0) return '0 B';
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;
};

interface ResourceDetailProps {
  isPromotion?: boolean;
}

interface PromotionRelation {
  relationId: number;
  promotionId: number;
  resourceId: number;
  promotion?: Promotion;
}

const ResourceDetail = ({ isPromotion = false }: ResourceDetailProps) => {
  const { id, promotionId } = useParams<{ id?: string; promotionId?: string }>();
  const [resource, setResource] = useState<Resource | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [purchasing, setPurchasing] = useState(false);
  const [purchaseSuccess, setPurchaseSuccess] = useState(false);
  const [purchaseError, setPurchaseError] = useState<string | null>(null);
  const [downloading, setDownloading] = useState(false);
  const [downloadError, setDownloadError] = useState<string | null>(null);
  const [promotionRelations, setPromotionRelations] = useState<PromotionRelation[]>([]);
  const [activePromotion, setActivePromotion] = useState<Promotion | null>(null);

  const handlePurchase = async () => {
    if (!id || !resource) return;
    
    try {
      setPurchasing(true);
      setPurchaseError(null);
      
      // 调用积分购买接口
      await ResourceService.payPoints(id);
      
      // 购买成功
      setPurchaseSuccess(true);
      
      // 刷新资源信息
      const updatedResource = await ResourceService.getResourceById(id);
      setResource(updatedResource);
    } catch (err) {
      console.error('购买资源失败:', err);
      setPurchaseError(err instanceof Error ? err.message : '积分购买失败');
    } finally {
      setPurchasing(false);
    }
  };

  useEffect(() => {
    const fetchResource = async () => {
      try {
        setLoading(true);
        setError(null);
        
        if (isPromotion && promotionId) {
          // 获取促销活动相关的资源列表
          const data = await ResourceService.getPromotionResources(promotionId);
          setResource(data);
        } else if (id) {
          // 获取单个资源详情
          const data = await ResourceService.getResourceById(id);
          setResource(data);
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : '获取资源信息失败');
      } finally {
        setLoading(false);
      }
    };

    fetchResource();
  }, [id]);

  // 获取资源关联的促销活动信息
  useEffect(() => {
    const fetchPromotionRelations = async () => {
      if (!id) return;
      
      try {
        // 如果URL中有promotionId参数，直接获取该促销活动的详情
        if (promotionId) {
          console.log('URL中包含promotionId参数:', promotionId);
          try {
            console.log('直接调用getPromotionById, promotionId:', promotionId);
            const promotionDetail = await PromotionService.getPromotionById(promotionId);
            console.log('获取到的促销活动详情:', promotionDetail);
            
            // 检查获取到的促销活动是否在有效期内
            const now = new Date();
            const isInValidPeriod = 
              new Date(promotionDetail.startTime) <= now && 
              new Date(promotionDetail.endTime) >= now;
            
            console.log('促销活动是否在有效期内:', isInValidPeriod);
            console.log('促销活动是否激活:', promotionDetail.isActive);
            
            if (promotionDetail.isActive && isInValidPeriod) {
              console.log('设置有效的促销活动:', promotionDetail);
              setActivePromotion(promotionDetail);
              return; // 已找到有效促销活动，不需要继续获取资源关联的促销活动
            }
          } catch (err) {
            console.error('通过promotionId获取促销活动详情失败:', err);
          }
        }
        
        // 获取资源关联的促销活动
        console.log('开始获取资源关联的促销活动, 资源ID:', id);
        const promotions = await PromotionResourceService.getResourcePromotions(id);
        console.log('获取到的促销活动列表:', promotions);
        
        // 构建关系数据
        const relations: PromotionRelation[] = promotions.map(promotion => {
          // 确保promotionId存在
          const promotionId = promotion.promotionId || promotion.id;
          console.log('处理促销活动:', promotion, '提取的promotionId:', promotionId);
          
          return {
            relationId: parseInt(promotion.id),
            promotionId: parseInt(promotionId),
            resourceId: parseInt(id),
            promotion: promotion
          };
        });
        
        console.log('构建的促销关系数据:', relations);
        setPromotionRelations(relations);
        
        // 查找当前有效的促销活动（isActive为true且在有效期内的）
        const now = new Date();
        console.log('当前时间:', now);
        const active = promotions.find(p => {
          console.log('检查促销活动:', p);
          console.log('isActive:', p.isActive);
          console.log('startTime:', p.startTime, '是否早于当前时间:', new Date(p.startTime) <= now);
          console.log('endTime:', p.endTime, '是否晚于当前时间:', new Date(p.endTime) >= now);
          
          return p.isActive && 
            new Date(p.startTime) <= now && 
            new Date(p.endTime) >= now;
        });
        
        if (active) {
          console.log('找到有效的促销活动:', active);
          setActivePromotion(active);
        } else if (promotions.length > 0) {
          console.log('未找到有效的促销活动，尝试获取第一个促销活动的详情');
          console.log('第一个促销活动:', promotions[0]);
          
          // 确保promotionId存在
          const firstPromotionId = promotions[0].promotionId || promotions[0].id;
          console.log('提取的promotionId:', firstPromotionId);
          
          // 如果没有找到有效的促销活动，但有关联的促销活动，获取第一个促销活动的详细信息
          if (firstPromotionId) {
            try {
              console.log('调用getPromotionById, promotionId:', firstPromotionId);
              const promotionDetail = await PromotionService.getPromotionById(firstPromotionId);
              console.log('获取到的促销活动详情:', promotionDetail);
              
              // 检查获取到的促销活动是否在有效期内
              const isInValidPeriod = 
                new Date(promotionDetail.startTime) <= now && 
                new Date(promotionDetail.endTime) >= now;
              
              console.log('促销活动是否在有效期内:', isInValidPeriod);
              console.log('促销活动是否激活:', promotionDetail.isActive);
              
              if (promotionDetail.isActive && isInValidPeriod) {
                console.log('设置有效的促销活动:', promotionDetail);
                setActivePromotion(promotionDetail);
              }
            } catch (err) {
              console.error('获取促销活动详情失败:', err);
            }
          }
        }
      } catch (error) {
        console.error('获取资源关联的促销活动失败:', error);
      }
    };

    fetchPromotionRelations();
  }, [id, promotionId]);

  const handleDownload = async () => {
    if (!id || !resource) return;
    
    try {
      setDownloading(true);
      setDownloadError(null);
      
      // 调用下载资源接口获取blob数据
      const blob = await ResourceService.downloadResource(id);
      
      // 创建blob URL
      const url = window.URL.createObjectURL(blob);
      
      // 创建一个隐藏的a标签来下载文件
      const link = document.createElement('a');
      link.href = url;
      // 确保文件名以.torrent结尾
      const fileName = resource.title || 'download';
      const fileNameWithExt = fileName.endsWith('.torrent') ? fileName : `${fileName}.torrent`;
      link.setAttribute('download', fileNameWithExt);
      document.body.appendChild(link);
      link.click();
      
      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url); // 释放blob URL
    } catch (err) {
      console.error('下载资源失败:', err);
      setDownloadError(err instanceof Error ? err.message : '下载资源失败');
    } finally {
      setDownloading(false);
    }
  };

  // 计算折扣后的积分
  const calculateDiscountedPoints = () => {
    if (!resource || !activePromotion) return resource?.points || 0;
    
    // 计算折扣后的积分
    const originalPoints = resource.points || 0;
    const discount = activePromotion.discount || 1; // 默认为1表示无折扣
    return Math.floor(originalPoints * discount);
  };

  if (loading) {
    return (
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Box display="flex" justifyContent="center" p={3}>
          <CircularProgress />
        </Box>
      </Container>
    );
  }

  if (error) {
    return (
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Alert severity="error">{error}</Alert>
      </Container>
    );
  }

  if (!resource) {
    return (
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Alert severity="info">资源不存在</Alert>
      </Container>
    );
  }

  // 资源详情界面
  return (
    <Container maxWidth="md" sx={{ py: 4 }}>
      <Paper sx={{ p: 4 }}>
        <Grid container spacing={4}>
          <Grid item xs={12} md={4}>
            <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
              <img
                src={resource.coverImageUrl || resource.coverUrl || '/covers/movie_cover_2.jpg'}
                alt={resource.title}
                style={{ width: 240, height: 320, objectFit: 'cover', borderRadius: 8 }}
              />
              <Box sx={{ mt: 2, textAlign: 'center' }}>
                <Typography variant="body1" color="text.secondary" sx={{ mb: 1 }}>
                  {activePromotion ? (
                    <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Typography 
                          variant="body2" 
                          color="text.secondary" 
                          sx={{ textDecoration: 'line-through' }}
                        >
                          原价: {resource.points} 积分
                        </Typography>
                      </Box>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Typography variant="body1" color="error" fontWeight="bold">
                          促销价: {calculateDiscountedPoints()} 积分
                        </Typography>
                        <Chip 
                          label={`${activePromotion.discount * 10}折`} 
                          color="error" 
                          size="small" 
                          variant="outlined"
                        />
                      </Box>
                    </Box>
                  ) : (
                    <>所需积分：{resource.points !== undefined ? resource.points : 0} 积分</>
                  )}
                </Typography>
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                  {/* 根据isPay属性动态渲染按钮 */}
                  {!resource.isPay ? (
                    <Button
                      variant="contained"
                      color="primary"
                      sx={{ width: 200 }}
                      onClick={handlePurchase}
                      disabled={purchasing}
                    >
                      {purchasing ? '购买中...' : '购买资源'}
                    </Button>
                  ) : (
                    <Button
                      variant="contained"
                      color="secondary"
                      sx={{ width: 200 }}
                      onClick={handleDownload}
                      disabled={downloading}
                    >
                      {downloading ? '下载中...' : '下载资源'}
                    </Button>
                  )}
                </Box>
              </Box>
              
              {purchaseError && (
                <Alert severity="error" sx={{ mt: 2 }}>
                  {purchaseError}
                </Alert>
              )}
              
              {downloadError && (
                <Alert severity="error" sx={{ mt: 2 }}>
                  {downloadError}
                </Alert>
              )}
              
              <Snackbar
                open={purchaseSuccess}
                autoHideDuration={6000}
                onClose={() => setPurchaseSuccess(false)}
                message="积分购买成功！"
              />
            </Box>
          </Grid>
          <Grid item xs={12} md={8}>
            <Typography variant="h4" gutterBottom>{resource.title}</Typography>
            
            <Divider sx={{ my: 2 }} />
            <Box sx={{ mb: 2 }}>
              <Typography variant="body1" sx={{ mb: 1 }}>
                上传者：{resource.uploaderName}
              </Typography>
              <Typography variant="body1" sx={{ mb: 1 }}>
                上传时间：{resource.uploadTime ? new Date(resource.uploadTime).toLocaleString() : '-'}
              </Typography>
              <Typography variant="body1" sx={{ mb: 1 }}>
                资源描述：{resource.description ?? '-'}
              </Typography>
              <Typography variant="body1" sx={{ mb: 1 }}>
                文件大小：{resource.size ? formatSize(resource.size) : '-'}
              </Typography>
              <Typography variant="body1" sx={{ mb: 1 }}>
                购买次数：{resource.downloadCount || 0}
              </Typography>
            </Box>
            
            {/* 促销活动信息区域 */}
            {activePromotion && (
              <Box sx={{ mb: 3, p: 2, bgcolor: 'rgba(255, 0, 0, 0.05)', borderRadius: 2, border: '1px dashed #f44336' }}>
                <Typography variant="h6" color="error" gutterBottom>
                  <LocalOfferIcon sx={{ mr: 1, verticalAlign: 'middle' }} />
                  促销活动: {activePromotion.promotionTitle}
                </Typography>
                <Typography variant="body2" paragraph>
                  {activePromotion.promotionRule}
                </Typography>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Typography variant="body2" color="text.secondary">
                    有效期: {new Date(activePromotion.startTime).toLocaleDateString()} - {new Date(activePromotion.endTime).toLocaleDateString()}
                  </Typography>
                  <Chip 
                    label={`${activePromotion.discount * 10}折`} 
                    color="error" 
                    size="small"
                    sx={{ fontWeight: 'bold' }}
                  />
                </Box>
              </Box>
            )}
            
            {resource.tags && Array.isArray(resource.tags) && resource.tags.length > 0 && (
              <Box sx={{ mb: 2 }}>
                <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>标签：</Typography>
                {resource.tags.map((tag: string, index: number) => (
                  <Chip key={index} label={tag} sx={{ mr: 0.5, mb: 0.5 }} />
                ))}
              </Box>
            )}
            
            <Divider sx={{ my: 2 }} />
            <ResourcePromotions resourceId={resource.id} />
          </Grid>
        </Grid>
      </Paper>
    </Container>
  );
};

export default ResourceDetail;